using System;
using System.Collections;

namespace MSHelpLib.BaseCode
{
	/// <summary>
	/// Summary description for PathMgr.
	/// </summary>
	public class PathMgr
	{
		private string m_Path="";
		private string m_Dir="";
		private string m_Drive="";
		private string m_ServerName="";

		private ArrayList segs;

        /// <summary>
        /// Initializes a new instance of the <see cref="PathMgr"/> class.
        /// </summary>
        /// <param name="Path">The path.</param>
		public PathMgr(string Path)
		{
			m_Path=Path.Replace("/",@"\");
			segs=new ArrayList();

			m_Dir=m_Path;
			if ((m_Path.Length>2) && (m_Path[1]==':'))
			{
				m_Drive=m_Path.Substring(0,2);
				m_Dir=m_Path.Substring(3);
			}
			else if ((m_Path.Length>4) && (m_Path.StartsWith(@"\\")))
			{
				int idx=m_Path.IndexOf(@"\",2);
				if (idx==-1)
					m_ServerName=m_Path.Substring(2);
				else
				{
					m_ServerName=m_Path.Substring(2,idx-2);
					m_Dir=m_Path.Substring(idx+1);
				}
			}
			else
			{
				m_Dir=m_Path;
				m_Path="";
			}
			
			string [] parts=m_Dir.Split('\\');
			foreach(string p in parts)
			{
				if (p!="")
					segs.Add(p);
			}
		}

        /// <summary>
        /// Gets the path.
        /// </summary>
        /// <value>The path.</value>
		public string Path
		{
			get
			{
				// Build Path.
				string NewPath="";
				if (m_ServerName!="")
					NewPath+=@"\\"+m_ServerName;
				else if (m_Drive!="")
					NewPath+=m_Drive;
				else
					NewPath+=@"\";

				bool bFirst=true;
				foreach(string s in segs)
				{
					if (!bFirst)
						NewPath+=@"\";
					bFirst=false;
					NewPath+=s;
				}

				return NewPath;
			}
		}

        /// <summary>
        /// Moves up.
        /// </summary>
		public void MoveUp()
		{
			if (segs.Count>0)
				segs.RemoveAt(segs.Count-1);
		}

        /// <summary>
        /// Gets the segment.
        /// </summary>
        /// <param name="i">The i.</param>
        /// <returns></returns>
		public string GetSegment(int i)
		{
			if (i>segs.Count) return "";
			if (i<0) return "";
			return (string)segs[i];
		}

        /// <summary>
        /// Gets the segment count.
        /// </summary>
        /// <value>The segment count.</value>
		public int SegmentCount
		{
			get
			{
				return segs.Count;
			}
		}

        /// <summary>
        /// Combines the path.
        /// </summary>
        /// <param name="relativePath">The relative path.</param>
        /// <returns></returns>
		public bool CombinePath(string relativePath)
		{			
			PathMgr relPath=new PathMgr(relativePath);
			if (relPath.m_ServerName!="")
				return false;
			if (relPath.m_Drive!="")
				return false;

			for(int i=0;i<relPath.SegmentCount;i++)
			{
				string seg=relPath.GetSegment(i);
				if (seg=="..")
					MoveUp();
				else
					segs.Add(seg);
			}
			return true;
		}
	}
}
